package com.yq.ylmall.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yq.ylmall.dto.user.UserInfoDto;
import com.yq.ylmall.dto.user.UserRegisterDto;
import com.yq.ylmall.exception.ServiceException;
import com.yq.ylmall.model.user.UserInfo;
import com.yq.ylmall.result.ResultCode;
import com.yq.ylmall.user.mapper.UserInfoMapper;
import com.yq.ylmall.user.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.ylmall.vo.user.UserInfoPageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author cherry
 * @since 2024-06-03
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Override
    public List<UserInfo> findAll() {
        return baseMapper.selectList(null);
    }

    @Override
    public IPage<UserInfoPageVo> queryUserInfoByPage(UserInfoDto userInfoDto) {
        Page<UserInfoPageVo> iPage =  new Page<>(userInfoDto.getPageNum(),userInfoDto.getPageSize());
        baseMapper.selectUserInfoPage(iPage,userInfoDto);
        return iPage;

//        Page<UserInfoPageVo> userInfoPageVoPage = new Page<>();
//        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
//        List<UserInfo> userInfoList = baseMapper.selectList(wrapper);

    }

    @Override
    public Boolean stopUserStatusById(Long userId,Integer status) {
        UserInfo user = new UserInfo();
        user.setId(userId);
        user.setStatus(status);
        int row = baseMapper.updateById(user);
        if (row==1) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public UserInfo getUserInfoUsername(String username) {
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        UserInfo userInfo = this.baseMapper.selectOne(queryWrapper);
        return userInfo;
    }

    @Override
    public void saveUserInfo(UserRegisterDto dto){
        String username = dto.getUsername();
        UserInfo selectedByUsername = getUserInfoUsername(username);
        if (selectedByUsername !=null){
            throw new ServiceException(ResultCode.THE_USERNAME_HAS_BEEN_REGISTERED);
        }
        UserInfo userInfo = new UserInfo();
        BeanUtil.copyProperties(dto ,userInfo);
        userInfo.setStatus(1);
        int rows =baseMapper.insert(userInfo);
        if (rows != 1){
            throw new ServiceException(ResultCode.USER_REGISTRATION_FAILED);
        }
    }

}
